<?php
/**
 * Created by PhpStorm.
 * User: chenxuyi
 * Date: 2018/3/3
 * Time: 下午2:54
 */

namespace App\Forms;

use App\Constant\CacheConstant;
use App\Constant\TokenConstant;
use App\Exceptions\ApiException;
use App\ModelCases\AdminUserMC;
use Cache;

class AdminUserForm extends BaseForm
{

    public function login()
    {
        $privatekey = openssl_pkey_get_private(config('rsa.login_pri_key'));
        $data       = base64_decode($this->password);
        openssl_private_decrypt($data, $password, $privatekey, OPENSSL_PKCS1_OAEP_PADDING);
        $admin = AdminUserMC::getByName($this->username);
        if (!$admin) {
            throw new ApiException('用户不存在');
        }
        if (!password_verify($password, $admin->admin_user_password)) {
            throw new ApiException('密码错误');
        }

        $token = uniqid(TokenConstant::ADMIN_LOGIN_TOKEN_PREFIX, true).'.'.md5(microtime());
        Cache::put($token, $admin->toArray(), CacheConstant::TIMEOUT_HOUR_12);

        return [
            'token' => $token,
            'user'  => [
                'admin_user_name'   => $admin->admin_user_name,
                'admin_user_phone'  => $admin->admin_user_phone,
                'admin_user_email'  => $admin->admin_user_email,
                'admin_user_status' => $admin->admin_user_status,
            ],
        ];
    }

}